package com.atguigu.daijia.driver.service.impl;

import com.alibaba.nacos.common.codec.Base64;
import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.mapper.DriverInfoMapper;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.driver.service.OcrService;
import com.atguigu.daijia.model.entity.driver.DriverInfo;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.atguigu.daijia.model.vo.driver.DriverLicenseOcrVo;
import com.atguigu.daijia.model.vo.driver.IdCardOcrVo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.DriverLicenseOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OcrServiceImpl implements OcrService {


    @Resource
    private TencentCloudProperties tencentCloudProperties;
    @Resource
    private CosService cosService;
    @Resource
    private DriverInfoMapper driverInfoMapper;
    /**
     * 身份证OCR识别
     * 使用腾讯云OCR服务从图片中提取身份证信息
     *
     * @param file 图片文件
     * @return IdCardOcrVo 身份证信息提取结果
     */
    @Override
    public IdCardOcrVo idCardOcr(MultipartFile file,Long driverId) {
        try{
            // 创建腾讯云凭证实例
            Credential cred = new Credential(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
            // 创建HTTP配置实例
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 创建客户端配置实例
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 创建OCR客户端
            OcrClient client = new OcrClient(cred, tencentCloudProperties.getRegion(), clientProfile);
            // 创建身份证OCR请求实例
            IDCardOCRRequest req = new IDCardOCRRequest();
            // 将文件转换为Base64编码字符串
            req.setImageBase64(new String(Base64.encodeBase64(file.getBytes())));
            // 发送OCR请求并获取响应
            IDCardOCRResponse resp = client.IDCardOCR(req);

            // 初始化身份证OCR结果对象
            IdCardOcrVo idCardOcrVo = new IdCardOcrVo();
            // 处理身份证正面信息
            if (StringUtils.hasText(resp.getName())) {
                idCardOcrVo.setName(resp.getName());
                idCardOcrVo.setGender("男".equals(resp.getSex()) ? "1" : "2");
                idCardOcrVo.setBirthday(DateTimeFormat.forPattern("yyyy/MM/dd").parseDateTime(resp.getBirth()).toDate());
                idCardOcrVo.setIdcardNo(resp.getIdNum());
                idCardOcrVo.setIdcardAddress(resp.getAddress());

                // 上传身份证正面图片到腾讯云COS
                CosUploadVo cosUploadVo = cosService.upload(file, "idCard");
                idCardOcrVo.setIdcardFrontUrl(cosUploadVo.getUrl());
                idCardOcrVo.setIdcardFrontShowUrl(cosUploadVo.getShowUrl());

//                driverInfoMapper.update(null,new LambdaUpdateWrapper<DriverInfo>().
//                        set(DriverInfo::getName,idCardOcrVo.getName()).
//                        set(DriverInfo::getGender,idCardOcrVo.getGender()).
//                        set(DriverInfo::getBirthday,idCardOcrVo.getBirthday()).
//                        set(DriverInfo::getIdcardNo,idCardOcrVo.getIdcardNo()).
//                        set(DriverInfo::getIdcardAddress,idCardOcrVo.getIdcardAddress()).
//                        set(DriverInfo::getIdcardFrontUrl,idCardOcrVo.getIdcardFrontUrl()).
//                        eq(DriverInfo::getId,driverId));
            } else {
                // 处理身份证反面信息
                String idcardExpireString = resp.getValidDate().split("-")[1];
                idCardOcrVo.setIdcardExpire(DateTimeFormat.forPattern("yyyy.MM.dd").parseDateTime(idcardExpireString).toDate());

                // 上传身份证反面图片到腾讯云COS
                CosUploadVo cosUploadVo = cosService.upload(file, "idCard");
                idCardOcrVo.setIdcardBackUrl(cosUploadVo.getUrl());
                idCardOcrVo.setIdcardBackShowUrl(cosUploadVo.getShowUrl());
//                driverInfoMapper.update(null,new LambdaUpdateWrapper<DriverInfo>().
//                        set(DriverInfo::getIdcardExpire,idCardOcrVo.getIdcardExpire()).
//                        set(DriverInfo::getIdcardBackUrl,idCardOcrVo.getIdcardBackUrl()).
//                        eq(DriverInfo::getId,driverId));

            }


            // 返回身份证信息提取结果
            return idCardOcrVo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }
    }

    @Override
    public DriverLicenseOcrVo driverLicenseOcr(MultipartFile file,Long driverId) {
        try{
            // 创建腾讯云凭证实例
            Credential cred = new Credential(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
            // 创建HTTP配置实例
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 创建客户端配置实例
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 创建OCR客户端
            OcrClient client = new OcrClient(cred, tencentCloudProperties.getRegion(), clientProfile);
            // 创建身份证OCR请求实例
            DriverLicenseOCRRequest req = new DriverLicenseOCRRequest();
            // 将文件转换为Base64编码字符串
            req.setImageBase64(new String(Base64.encodeBase64(file.getBytes())));
            // 发送OCR请求并获取响应
            DriverLicenseOCRResponse resp = client.DriverLicenseOCR(req);

            DriverLicenseOcrVo driverLicenseOcrVo = new DriverLicenseOcrVo();
            if (StringUtils.hasText(resp.getName())) {
                //驾驶证正面
                //驾驶证名称要与身份证名称一致
                driverLicenseOcrVo.setName(resp.getName());
                driverLicenseOcrVo.setDriverLicenseClazz(resp.getClass_());
                driverLicenseOcrVo.setDriverLicenseNo(resp.getCardCode());
                driverLicenseOcrVo.setDriverLicenseIssueDate(DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(resp.getDateOfFirstIssue()).toDate());
                driverLicenseOcrVo.setDriverLicenseExpire(DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(resp.getEndDate()).toDate());

                //上传驾驶证反面图片到腾讯云cos
                CosUploadVo cosUploadVo = cosService.upload(file, "driverLicense");
                driverLicenseOcrVo.setDriverLicenseFrontUrl(cosUploadVo.getUrl());
                driverLicenseOcrVo.setDriverLicenseFrontShowUrl(cosUploadVo.getShowUrl());
//                driverInfoMapper.update(null,new LambdaUpdateWrapper<DriverInfo>().
//                        set(DriverInfo::getDriverLicenseClazz,driverLicenseOcrVo.getDriverLicenseClazz()).
//                        set(DriverInfo::getDriverLicenseNo,driverLicenseOcrVo.getDriverLicenseNo()).
//                        set(DriverInfo::getDriverLicenseIssueDate,driverLicenseOcrVo.getDriverLicenseIssueDate()).
//                        set(DriverInfo::getDriverLicenseExpire,driverLicenseOcrVo.getDriverLicenseExpire()).
//                        set(DriverInfo::getDriverLicenseFrontUrl,driverLicenseOcrVo.getDriverLicenseFrontUrl()).
//                        eq(DriverInfo::getId,driverId));
            } else {
                //驾驶证反面
                //上传驾驶证反面图片到腾讯云cos
                CosUploadVo cosUploadVo =  cosService.upload(file, "driverLicense");
                driverLicenseOcrVo.setDriverLicenseBackUrl(cosUploadVo.getUrl());
                driverLicenseOcrVo.setDriverLicenseBackShowUrl(cosUploadVo.getShowUrl());

//                driverInfoMapper.update(null,new LambdaUpdateWrapper<DriverInfo>().
//                        set(DriverInfo::getDriverLicenseBackUrl,driverLicenseOcrVo.getDriverLicenseBackUrl()).
//                        eq(DriverInfo::getId,driverId));
            }

            // 返回驾驶证信息提取结果
            return driverLicenseOcrVo;
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }
    }


}
